package com.wgu.modules.service.impl;

import com.wgu.common.mapper.BeanMapper;
import com.wgu.common.utils.Assert;
import com.wgu.entity.Type;
import com.wgu.modules.dto.TypeDTO;
import com.wgu.modules.mapper.TypeMapper;
import com.wgu.modules.repository.TypeRepository;
import com.wgu.modules.service.TypeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 书籍类型实现类
 * @Author: w
 * @Date: 2019/7/1 15:43
 * @Version 1.0
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class TypeServiceImpl implements TypeService {
    @Resource
    private TypeRepository typeRepository;
    @Resource
    private TypeMapper typeMapper;
    @Resource
    private BeanMapper beanMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(TypeDTO typeDTO) {
        if(typeDTO.getParentId()!=null){
            Assert.isTrue(typeRepository.existsById(typeDTO.getParentId()),"此id不存在");
        }
        Type type = new Type();
        beanMapper.mapper(typeDTO,type);
        typeRepository.save(type);
    }

    @Override
    public List<TypeDTO> getsType() {
        // 获取所有类型
        List<Type> list = typeRepository.findAll();
        return typeMapper.toDto(list);
    }

    @Override
    public List<TypeDTO> getsParent() {
        // 获取所有级别为1的书籍类型
        List<Type> list = typeRepository.findByLevel("1");
        return typeMapper.toDto(list);
    }

    @Override
    public Type getType(String name) {
        return typeRepository.findByTypeName(name);
    }
}
